<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="resetForm"
      />
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer
        style="margin-bottom: 10px; display: flex; align-items: center"
      >
        <div><Button icon="add" @click="handleAdd">新增</Button></div>
        <!-- <div><Button icon="export" @click="handleImport">导入</Button></div> -->
        <!-- <div><Button icon="" @click="handleJc">继承</Button></div> -->
        <div>
          <!-- <Button icon="export" @click="handleUploadTemple">下载模板</Button> -->
        </div>
      </OperationContainer>
      <el-table
        v-loading="tableLoading"
        height="100%"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
      >
        <el-table-column align="center" type="index" label="" width="60" />
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="year" label="年" />
        <el-table-column prop="month" label="月" />
        <el-table-column prop="employeecode" label="职工编号" />
        <el-table-column prop="employeename" label="职工姓名" />
        <el-table-column prop="deptcode" label="科室名称" />
        <el-table-column prop="deptname" label="科室编号" />
        <el-table-column prop="rulecode" label="系数" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <i
              class="el-icon-edit-outline"
              style="
                padding-top: 4px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleEdit(scope.row)"
            />
            <i
              class="el-icon-delete"
              style="
                padding-top: 4px;
                padding-left: 10px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      />

      <!-- 新增、编辑 -->
      <Dialog
        :title="title"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="dialogVisible = false"
        @confirm="handleConfirm"
      >
        <el-form ref="form" :model="formInfo" label-width="60px" size="small">
          <el-form-item label="员工：">
            <el-select
              v-model="formInfo.employeecode"
              placeholder="请选择"
              filterable
              remote
              :remote-method="deptFilter"
            >
              <el-option
                v-for="item in workerPerson"
                :key="item.empId"
                :label="item.empName"
                :value="item.empId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室：">
            <el-select
              v-model="formInfo.deptCode"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in deptDataList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="系数：">
            <el-input
              v-model="formInfo.ruleCode"
              placeholder="请输入"
              @blur="
                formInfo.ruleCode = formInfo.ruleCode.replace(/[^\d.?]/g, '')
              "
            ></el-input>
          </el-form-item>
        </el-form>
      </Dialog>

      <!--导入 -->
      <Dialog
        title="导入数据"
        :visible="drVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="drVisible = false"
        @confirm="handleDrConfirm"
      >
        <el-form ref="form" :model="formInfo" label-width="90px" size="small">
          <el-form-item label="员工工号：">
            <!-- <el-select
              v-model="formInfo.edExtraFirstCode"
              placeholder="请选择"
              :disabled="title == '编辑'"
              filterable
            >
              <el-option
                v-for="item in workerPerson"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="员工姓名：">
            <!-- <el-select
              v-model="formInfo.edExtraFirstCode"
              placeholder="请选择"
              :disabled="title == '编辑'"
              filterable
            >
              <el-option
                v-for="item in workerPerson"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="科室名称：">
            <el-select
              v-model="formInfo.edExtraSecondCode"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in dptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室代码：">
            <el-select
              v-model="formInfo.edExtraSecondCode"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in dptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分摊系数：">
            <el-select
              v-model="formInfo.edExtraSecondCode"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in xsList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件：">
            <el-upload
              :show-file-list="false"
              class="upload-demo"
              action
              :auto-upload="false"
              :on-change="handlechange"
            >
              <el-button size="mini" type="primary">导入文件</el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div> -->
            </el-upload>
          </el-form-item>
        </el-form>
      </Dialog>
      <!--继承 -->
      <Dialog
        title="继承"
        :visible="jcVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="jcVisible = false"
        @confirm="handleJcConfirm"
      >
        <el-form
          ref="form"
          :model="inheritForm"
          label-width="100px"
          size="small"
        >
          <el-form-item label="继承年/月：">
            <el-select
              v-model="inheritForm.jcYearMoth"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in dateList"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import { getDepartmentSource } from "../../../utils/apis/accountingUnit/dept";
import {
  selectworkfactor,
  getYearMonth,
  addRoleworkfactor,
  getAllEmployeename,
  modifyworkfactor,
  Deleteinformation,
  getbyid,
  insertRoleworkfactor,
} from "../../../utils/apis/integrate/index";
import { Multirole } from "../../../utils/integrate";
export default {
  name: "Roles", // 科室-工资对应
  components: {},
  data() {
    return {
      inheritForm: {
        currentYearMonth: "",
        jcYearMoth: "",
      },
      jcVisible: false,
      deptDataList: [],
      fileList: [],
      drVisible: false,
      xsList: [],
      workerPerson: [],
      dptList: [],
      formInfo: {
        employeecode: "",
        deptCode: "",
        ruleCode: "",
      },
      dialogVisible: false,
      title: "",
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      filterElements: [
        {
          value: "",
          itemLabel: "value",
          itemValue: "value",
          label: "年/月",
          key: "yearMonth",
          type: "Select",
          options: [],
        },
        {
          filterable: true,
          clearable: true,
          value: "",
          itemLabel: "empName",
          itemValue: "empId",
          label: "职工",
          key: "employeecode",
          type: "Select",
          options: [],
          width: 210,
          remote: true,
          remoteMethod: this.deptFilter,
        },
      ],
      tableData: [],
      tableLoading: false,
      newParamList: {},
      rowId: "",
      dateList: [],
    };
  },
  created() {
    this.getYearMonthList();
    this.getDeptList();
    // this.getWorkList();
  },
  methods: {
    deptFilter(val) {
      getAllEmployeename({
        empName: val,
      }).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data;
          this.workerPerson = res.data.data;
        }
      });
    },
    handleJcConfirm() {
      if (!this.inheritForm.jcYearMoth) {
        this.$message.warning("请选择继承年月");
        return;
      }
      let param = {
        // lastMonth: this.inheritForm.jcYearMoth.split("-")[1],
        // lastYear: this.inheritForm.jcYearMoth.split("-")[0],
        // thisMonth: new Date().getMonth() + 1 + "",
        // thisYear: new Date().getFullYear() + "",
        yearMonth: this.inheritForm.jcYearMoth,
      };
      insertRoleworkfactor(param).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.message);
          this.getData();
          this.jcVisible = false;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    handleDrConfirm() {
      //确认导入
    },
    getDeptList() {
      getDepartmentSource({
        projectId: "1",
        SysId: "Cost",
      }).then((res) => {
        if (res.data.code === 200) {
          this.deptDataList = res.data.data;
        }
      });
    },
    getWorkList() {
      getAllEmployeename().then((res) => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data;
          this.workerPerson = res.data.data;
        }
      });
    },
    getYearMonthList() {
      getYearMonth().then((res) => {
        if (res.data.code === 200) {
          this.filterElements[0].options = res.data.data;
          this.dateList = res.data.data;
          this.$nextTick(() => {
            this.filterElements[0].value = res.data.data[0].value;
          });
        }
      });
    },
    handlechange(file, fileList) {
      console.log("file", file);
      console.log("fileList", fileList);
      let fileType = file.name.substr(file.name.lastIndexOf(".")).trim();
      if (fileType !== ".xlsx" && fileType !== ".xls") {
        this.$message.warning("请选择Excel格式的文件导入！");
        this.fileList = [];
        return;
      }
      let files = file.raw;
      let formData = new FormData();
      formData.append("file", files);
      // AddHealthSurveyExcel(formData).then((res) => {
      //   if (res.data.code === 200) {
      //     this.$message.success("导入成功");
      //     this.fileList = [];
      //   } else {
      //     this.$message.error(res.data.message);
      //     this.fileList = [];
      //   }
      // });
    },
    handleDelete(row) {
      //删除
      let param = [row.id];
      this.$confirm({
        title: "温馨提示",
        content: "您确定要删除该条数据?",
        okText: "确定",
        cancelText: "取消",
        okFn: () => {
          Deleteinformation(param).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message);
              this.pageAttr.currentPage = 1;
              this.getData();
            } else {
              this.$message.error(res.data.message);
            }
          });
        },
        cancelFn: () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        },
      });
    },
    getData() {
      // 列表
      let multiRole = new Multirole();
      multiRole.employeecode = this.newParamList.employeecode;
      multiRole.month =
        (this.newParamList.yearMonth &&
          this.newParamList.yearMonth.split("-")[1]) ||
        "";
      multiRole.year =
        (this.newParamList.yearMonth &&
          this.newParamList.yearMonth.split("-")[0]) ||
        "";
      multiRole.pageIndex = this.pageAttr.currentPage;
      multiRole.pageSize = this.pageAttr.pageSize;
      this.tableLoading = true;
      selectworkfactor(multiRole).then((res) => {
        if (res.data.code === 200) {
          this.tableLoading = false;
          this.tableData = res.data.data.list;
          this.pageAttr.total = res.data.data.total || 0;
        }
      });
    },
    handleConfirm() {
      //确定
      if (!this.formInfo.employeecode) {
        this.$message.warning("请选择员工");
        return;
      }
      if (!this.formInfo.deptCode) {
        this.$message.warning("请选择科室");
        return;
      }
      let multiRole = new Multirole();
      multiRole.employeecode = this.formInfo.employeecode;
      multiRole.employeename = this.workerPerson.find(
        (item) => item.empId == this.formInfo.employeecode
      ).empName;
      multiRole.deptcode = this.formInfo.deptCode;
      multiRole.deptname = this.deptDataList.find(
        (item) => item.deptCode == this.formInfo.deptCode
      ).deptName;
      multiRole.rulecode = this.formInfo.ruleCode;
      if (this.title == "新增") {
        addRoleworkfactor(multiRole).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
            this.dialogVisible = false;
            this.getYearMonthList();
            this.getData();
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else {
        multiRole.id = this.rowId;
        modifyworkfactor(multiRole).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
            this.dialogVisible = false;
            this.getData();
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    resetForm() {
      location.reload();
    },
    handleSearch(value) {
      this.newParamList = value;
      this.pageAttr.currentPage = 1;
      this.getData();
    },
    handleEdit(row) {
      this.handleClearForm();
      this.rowId = row.id;
      getbyid(row.id).then((res) => {
        if (res.data.code === 200) {
          this.formInfo.employeecode = res.data.data.employeecode;
          this.formInfo.ruleCode = res.data.data.rulecode;
          this.formInfo.deptCode = res.data.data.deptcode;
        }
      });
      this.title = "编辑";
      this.dialogVisible = true;
    },
    handleClearForm() {
      //清除新增/编辑form
      this.formInfo.employeecode = "";
      this.formInfo.ruleCode = "";
      this.formInfo.deptCode = "";
    },
    handleUploadTemple() {
      //下载模板
      const parms = {
        deptCode: this.ruleForm.deptCode,
        endDate:
          this.ruleForm.timeDate === "" || this.ruleForm.timeDate === null
            ? ""
            : this.ruleForm.timeDate[1],
        nurseCellCode: this.ruleForm.nurseCellCode,
        pageNum: this.pageInfor.pageNum,
        pageSize: this.pageInfor.pageSize,
        startDate:
          this.ruleForm.timeDate === "" || this.ruleForm.timeDate === null
            ? ""
            : this.ruleForm.timeDate[0],
        yard: this.ruleForm.region,
      };
      getManageBedCalculationDtoExcel(parms).then((res) => {
        const blob = new Blob([res.data]);
        const fileName = "数据报表集管床位计算报表" + ".xlsx";
        const URL = window.URL || window.webkitURL || window.moxURL;
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName; // 命名下载名称
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob); // 表示一个指定的file对象或Blob对象
          document.body.appendChild(elink);
          elink.click(); // 点击触发下载
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      });
    },
    handleJc() {
      //继承
      this.inheritForm.jcYearMoth = "";
      this.jcVisible = true;
    },
    handleImport() {
      //导入
      this.drVisible = true;
    },
    handleAdd() {
      //新增
      this.handleClearForm();
      this.title = "新增";
      this.dialogVisible = true;
    },
    // 分页
    pagationChange(payload) {
      console.log("payload", payload);
      this.pageAttr.currentPage = payload.page;
      this.pageAttr.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-upload {
  .el-button--primary {
    background-color: #217dfa;
    border-color: #217dfa;
  }
}
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
</style>
